<script setup lang="ts">
import { QForm, type FormItemRows } from '@meetjs/element-plus-kit'
import { type FormRules } from 'element-plus'
import { getDicts } from '@/api/system/dict/index'
import type { IGetDictsRes } from '@/api/system/dict/type'
import { addType, getType, updateType } from '@/api/system/dictType/index'
import type { DictTypeParams } from '@/api/system/dictType/type'

const emits = defineEmits<{
	refresh: []
}>()

const visible = ref(false)
const loading = ref(false)
const title = ref('新增字典类型')
const formRef = ref()

const baseFormData: DictTypeParams = {
	dictName: '',
	dictType: '',
	status: 0,
	remark: ''
}

const dialogFormValue = ref<DictTypeParams>({ ...baseFormData })
const sysNormalDisable = ref<IGetDictsRes>([])

const dialogOptions = ref<FormItemRows[]>([
	{
		type: 'input',
		label: '字典名称',
		prop: 'dictName'
	},
	{
		type: 'input',
		label: '字典类型',
		prop: 'dictType'
	},
	{
		type: 'radio',
		label: '状态',
		prop: 'status',
		options: sysNormalDisable as unknown as any,
		attrs: {
			style: {
				width: '200px'
			}
		}
	},
	{
		type: 'textarea',
		label: '备注',
		prop: 'remark',
		required: false,
		attrs: {
			rows: 3
		}
	}
])

const rules = reactive<FormRules<{ [k: string]: any }>>({
	dictName: [
		{
			required: true,
			message: '请输入字典名称'
		}
	],
	dictType: [
		{
			required: true,
			message: '请输入字典类型'
		}
	]
})

const init = async (operationType: 'add' | 'edit', id?: string, formData?: DictTypeParams) => {
	visible.value = true
	title.value = operationType === 'add' ? '新增字典类型' : '编辑字典类型'

	if (operationType === 'edit') {
		if (formData) {
			// 直接使用传入的数据
			dialogFormValue.value = { ...formData }
		} else if (id) {
			// 通过 API 获取数据
			loading.value = true
			try {
				const { data } = await getType(id)
				dialogFormValue.value = { ...data }
			} catch (error) {
				console.error('获取字典信息失败:', error)
				ElMessage.error('获取字典信息失败，请重试')
			} finally {
				loading.value = false
			}
		}
	} else {
		// 新增模式
		dialogFormValue.value = { ...baseFormData }
	}

	// 清理表单验证状态
	setTimeout(() => {
		formRef.value?.clearValidate()
	})
}

const submit = () => {
	formRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			loading.value = true
			try {
				const apiFunc = title.value === '新增字典类型' ? addType : updateType
				await apiFunc({ ...dialogFormValue.value })
				const message = title.value === '新增字典类型' ? '新增成功' : '修改成功'
				ElMessage.success(message)
				visible.value = false
				emits('refresh')
			} catch (error) {
				console.error('操作失败:', error)
				ElMessage.error('操作失败，请重试')
			} finally {
				loading.value = false
			}
		}
	})
}

const initOptions = () => {
	getDicts('sys_sys_normal_disable').then(data => {
		sysNormalDisable.value = data
		dialogOptions.value[2].options = data
	})
}

initOptions()

defineExpose({
	init
})
</script>

<template>
	<ElDialog
		v-model="visible"
		:title="title"
		:close-on-click-modal="false"
		width="500px"
	>
		<QForm
			ref="formRef"
			label-width="100px"
			:model="dialogFormValue"
			:form-options="dialogOptions"
			:rules="rules"
			:required="true"
		/>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button
				type="primary"
				:loading="loading"
				@click="submit"
			>
				确定
			</el-button>
		</template>
	</ElDialog>
</template>

<style scoped></style>
